<template>
  <VDialog
    @close="handleClose"
    title="人员管理"
    width="50%"
    @save="save"
    :loading="loading"
    :close-on-click-modal="false"
  >
    <template #content>
      <div class="m-[10px] mx-[20px] border border-[#dadce4] rounded-[10px]">
        <div
          v-if="data?.roleName"
          class="bg-[#F6FAFF] text-[#3487FF] text-[14px] text-center leading-[40px] rounded-tl-[10px] rounded-tr-[10px] tracking-[1px] border-b border-b-[#dadce4]"
        >
          {{ data.roleName }}
        </div>
        <el-cascader-panel
          v-model="personnel"
          :options="personnelList"
          :props="cascaderProps"
          ref="cascaderPanel"
          class="cascaderPanel"
        />
      </div>
    </template>
  </VDialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { organizationList } from "@/api/system/role";
import {
  cascaderProps,
  updateDepartmentIds,
  filterTreeByIds,
  transformIds,
  simplifyIds,
} from "./data";
const props = defineProps({
  data: { type: Object, default: () => {} },
  api: { type: Object, required: true },
});
const { data } = toRefs(props);
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);
const handleClose = async (refresh) => {
  personnel.value = [];
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
const cascaderPanel = ref();
const personnelList = ref([]);
const userIds = ref([]);
const getPersonnel = async () => {
  const { data } = await organizationList();
  const { updatedTree, duplicateUserIds } = updateDepartmentIds(data);
  personnelList.value = updatedTree || [];
  userIds.value = duplicateUserIds;
};
getPersonnel();
const personnel = ref([]);
watch(
  () => data.value?.userData,
  (val) => {
    let arr = transformIds(userIds.value, val || []);
    personnel.value = arr;
  }
);

const save = async () => {
  try {
    loading.value = true;
    const { parmas } = data.value;
    const selectedIds = cascaderPanel.value
      .getCheckedNodes()
      .map((item) => item.data.id)
      .filter((id) => typeof id === "string" && id.startsWith("d"));
    const filteredNodes = filterTreeByIds(personnelList.value, selectedIds);
    const depIds = filteredNodes.map((item) =>
      Number(item.id.replace("d", ""))
    );
    const userIds = simplifyIds(personnel.value);
    const { code, message } = await props.api({
      ...parmas,
      user_ids: userIds,
      dep_ids: depIds,
    });
    if (code !== 200) {
      ElMessage.error(message);
      return;
    }
    ElMessage.success("更新成功!");
    handleClose(true);
  } catch (error) {
    console.error("Save failed:", error);
    ElMessage.error("保存失败，请重试！");
  } finally {
    loading.value = false;
  }
};
</script>
<style lang="scss" scoped>
// .search {
//   margin: 10px;
//   box-sizing: content-box;
//   width: calc(100% - 20px);
//   border: none;

//   &:deep(.el-input__wrapper) {
//     padding: 1px 15px;
//     box-shadow: none;
//     background-color: #fafafa;
//   }
// }
.cascaderPanel {
  overflow: auto;
  height: 400px;
  border: none;
  border-top: 1px solid #dadce4;
  &:deep(.el-scrollbar__wrap) {
    height: 100% !important;
  }
}
</style>
